package com.wmcom.wm.filter;

import com.alibaba.fastjson.JSON;
import com.wmcom.wm.common.BaseContext;
import com.wmcom.wm.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            //请求地址
            String url=request.getRequestURI();
            //放行路径
        String [] str=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check = check(str, url);
         if (check) {
             filterChain.doFilter(request, response);
             return ;
         }
        if (request.getSession().getAttribute("employee")!=null) {
           long empid= (long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empid);
            long id = Thread.currentThread().getId();
            log.info("线程id"+id);
            filterChain.doFilter(request, response);
                    return;
            }
        if (request.getSession().getAttribute("user")!=null) {
            long userid= (long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);
            long id = Thread.currentThread().getId();
            log.info("线程id"+id);
            filterChain.doFilter(request, response);
            return;
        }
         response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String []str,String url){

            for (String st : str) {
                boolean match = PATH_MATCHER.match(st, url);
                if (match) {
                    return true;
                }
            }
            return false;
    }
}
